package com.quectel.sdk.dahua9100.monitor;

import com.fasterxml.jackson.databind.JsonNode;
import com.quectel.sdk.dahua9100.AbstractDahua9100BaseClient;
import com.quectel.sdk.dahua9100.basemodel.event.EventFaceData;
import com.quectel.sdk.dahua9100.monitor.model.DeviceGroupResp;
import com.quectel.sdk.dahua9100.monitor.model.DeviceResp;
import com.quectel.sdk.dahua9100.monitor.model.SnapFaceRecordResp;
import com.quectel.sdk.dahua9100.monitor.model.VideoPlaybackResp;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.ImageUtils;
import com.quectel.util.common.JacksonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 在这里编写说明
 *
 * @author: rananxin
 * @email: ryan.ran@quectel.com
 * @date: 2022-11-08 14:52:00
 */
public class MonitorClient extends AbstractDahua9100BaseClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(MonitorClient.class);
    private static final Integer PAGE_NO_NEXT_CODE = -1;

    /**
     * 获取时间段内的人脸抓拍
     *
     * @param startTime
     * @param endTime
     * @param pageHandlerFunction 每一页的处理
     * @return
     */
    public void fetchFaceRecord(List<String> codes, Date startTime, Date endTime, Consumer<List<SnapFaceRecordResp.ResultsCls>> pageHandlerFunction) {
        final String path = "/faceService/query/capture";
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("startCapTime", DateUtils.format(startTime, DateUtils.FormatType.TZ));
        conditionMap.put("endCapTime", DateUtils.format(endTime, DateUtils.FormatType.TZ));
        if (CollectionUtils.isNotEmpty(codes)) {
            conditionMap.put("channelCodes", codes);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("condition", conditionMap);

        int start = 1;
        int count = 0;
        final int limit = 999;
        int handCount = 0;
        while (true) {
            String resp = requester.post(path + "?start=" + count * limit + start + "&limit=" + limit, params);
            if (resp == null) {
                break;
            }
            SnapFaceRecordResp parse = JacksonUtils.parse(resp, SnapFaceRecordResp.class);
            if (parse == null) {
                break;
            }
            if (parse.getResults() == null || parse.getResults().size() <= 0) {
                break;
            }

            pageHandlerFunction.accept(parse.getResults());

            handCount += parse.getResults().size();
            if (handCount >= parse.getTotalCount()) {
                break;
            }

            count++;
        }
    }

    /**
     * @param msgId 第一次请求可以不传
     * @return left：msgId ； right： 人脸抓拍事件
     */
    public Pair<String, List<EventFaceData>> fetchFaceEvent(String msgId) {
        final String path = "/videoService/eventCenter/messages/subscribeAddress";
        String resp = requester.get(path, new HashMap<>());
        JsonNode respJson = JacksonUtils.parse(resp);

        String subscribeAddress = "https://" + respJson.get("subscribeAddress").asText();
        String imageAddress = respJson.get("imageAddress").asText();

        final String pollingPath = "/videoService/eventCenter/messages/subscribe";
        Map<String, Object> params = new HashMap<>();
        params.put("type", 8);
        if (StringUtils.isNotBlank(msgId)) {
            params.put("msgId", msgId);
        }

        List<EventFaceData> eventFaceData = new ArrayList<>();
        String eventResp = requester.get(subscribeAddress, pollingPath, params);
        JsonNode eventRespJson = JacksonUtils.parse(eventResp);
        String nextMsgId = eventRespJson.get("nextMsgId").asText();
        JsonNode resultsNodes = eventRespJson.get("results");
        for (JsonNode resultsNode : resultsNodes) {
            JsonNode eventNode = JacksonUtils.parse(resultsNode.asText());
            if (!"fcs.faceAnalysis".equals(eventNode.get("method").asText())) {
                continue;
            }
            EventFaceData parse = JacksonUtils.parse(resultsNode.asText(), EventFaceData.class);
            // 拼接url
            eventFaceData.add(parse);
        }
        return Pair.of(nextMsgId, eventFaceData);
    }

    /**
     * Step1：调用【分级获取组织】接口，先获取根组织节点ID，再循环获取根组织下的所有子组织节点，直到最末级组织节点。
     * Step2：循环调用【分级获取设备通道】接口，获取每个组织下的设备通道，nodeType=2表示设备，nodeType=3表示通道。
     * Step3：根据Step2中获取的通道编码
     */
    public List<DeviceResp.ResultsCls> drawResources() {

        final String path = "/videoService/devicesManager/deviceTree";

        Map<String, Object> params = new HashMap<>();
        params.put("nodeType", 1);
        params.put("typeCode", "01");
        params.put("pageSize", 999);
        List<DeviceGroupResp.ResultsCls> allGroupNodes = new ArrayList<>();
        Deque<String> noSeekGroups = new LinkedList<>();

        do {
            if (!noSeekGroups.isEmpty()) {
                String pop = noSeekGroups.pop();
                // 放入父组织id
                params.put("id", pop);
            }
            List<DeviceGroupResp.ResultsCls> pageGroups = new ArrayList<>();
            int page = 0;
            while (true) {
                // 分页获取组织
                params.put("page", ++page);
                String resp = requester.get(path, params);
                LOGGER.debug("大华9100 获取组织 params {} resp {}", params, resp);
                DeviceGroupResp deviceGroupResp = JacksonUtils.parse(resp, DeviceGroupResp.class);
                pageGroups.addAll(deviceGroupResp.getResults());
                if (pageGroups.size() >= deviceGroupResp.getTotalCount()
                        || PAGE_NO_NEXT_CODE.equals(deviceGroupResp.getNextPage())) {
                    break;
                }
            }

            if (!pageGroups.isEmpty()) {
                allGroupNodes.addAll(pageGroups);
                noSeekGroups.addAll(pageGroups.stream().map(DeviceGroupResp.ResultsCls::getId).collect(Collectors.toSet()));
            }
        } while (!noSeekGroups.isEmpty());

        List<DeviceResp.ResultsCls> result = new ArrayList<>();
        Map<String, Object> queryDeviceParams = new HashMap<>();
        queryDeviceParams.put("nodeType", 1);
        /*
         * typeCode : 类型string，必填。检索类型，值不同返回的内容不同。格式"orgType;showDev;catagory1,category2;unitType1,unitType2"
         *
         *  - orgType : 类型string，必填。表示获取的组织类型，默认01。注意：仅对管理员用户有意义，其它用户会根据角色所属的组织返回。当用户挂在业务组织下时，返回的orgType就表示用户所属组织。
         *
         *  - showDev : 类型string，选填。是否需要设备节点（0，不需要设备节点，1:需要设备节点），如果存在，一定要填category
         *
         *  - category : 类型string，选填。设备大类（编码器，卡口等，参考设备大类）。用,可以组合多个设备大类，多个大类按或的方式查询。ALL表示全部
         *
         *  - unitType : 类型string，选填。单元类型。参考单元类型。ALL表示全部
         *
         * 如果需要直接挂在组织下所有类型的设备或通道，可以这样使用: 查询组织"01"。 查询设备"01;1;ALL"。查询设备和通道"01;1;ALL;ALL"。仅查询通道"01;0;ALL;ALL"。
         */
        queryDeviceParams.put("typeCode", "01;0;5;1");
        queryDeviceParams.put("pageSize", 999);

        for (DeviceGroupResp.ResultsCls groupNode : allGroupNodes) {
            queryDeviceParams.put("id", groupNode.getId());

            List<DeviceResp.ResultsCls> pageDevices = new ArrayList<>();
            int page = 0;
            while (true) {
                queryDeviceParams.put("page", ++page);
                String resp = requester.get(path, queryDeviceParams);
                LOGGER.debug("大华9100 获取设备 params {} resp {}", queryDeviceParams, resp);
                DeviceResp deviceResp = JacksonUtils.parse(resp, DeviceResp.class);
                pageDevices.addAll(deviceResp.getResults());
                if (pageDevices.size() >= deviceResp.getTotalCount()
                        || PAGE_NO_NEXT_CODE.equals(deviceResp.getNextPage())) {
                    break;
                }
            }

            result.addAll(pageDevices);
        }

        return result;
    }

    public List<String> previewDefaultUrl(List<String> codeList) {
        return previewUrl(codeList, 0, "HLS");
    }

    /**
     * @param codeList 通道编号
     * @param subType  码流类型 0:主码流、1:辅流
     * @param scheme   协议类型 RTSP、FLV_HTTP、HLS
     * @return
     */
    public List<String> previewUrl(List<String> codeList, Integer subType, String scheme) {
        Map<String, Object> params = new HashMap<>();
        params.put("subType", subType);
        params.put("scheme", scheme);

        final String path = "/videoService/realmonitor/uri";

        List<String> urls = new ArrayList<>();
        for (String indexCode : codeList) {
            String url = "";
            params.put("channelId", indexCode);
            try {
                String resp = requester.get(path, params);
                LOGGER.debug("大华9100 获取视频流 params {} resp {}", params, resp);
                JsonNode respJson = JacksonUtils.parse(resp);
                url = respJson.get("url").asText();
            } catch (Exception e) {
                LOGGER.error("大华9100 监控点取流异常 indexCode {}", indexCode, e);
            }
            urls.add(url);
        }
        return urls;
    }

    public List<VideoPlaybackResp> defaultPlayback(String code, Date queryStartTime, Date queryEndTime) {
        return playback(code, queryStartTime, queryEndTime, "cloud", null);
    }

    /**
     * @param code           设备编号
     * @param queryStartTime 查询时间段
     * @param queryEndTime   查询时间段
     * @param location       录像位置 cloud | device
     * @param recordType     录像类型 normal | alarm | pluse | motionDetect
     * @return
     */
    public List<VideoPlaybackResp> playback(String code, Date queryStartTime, Date queryEndTime, String location
            , String recordType) {
        final String path = "/videoService/record/records";
        final String playbackPath = "/videoService/playback/uri";

        try {
            Map<String, Object> params = new HashMap<>();
            params.put("channelCode", code);
            params.put("beginTime", DateUtils.format(queryStartTime, DateUtils.FormatType.TZ));
            params.put("endTime", DateUtils.format(queryEndTime, DateUtils.FormatType.TZ));
            params.put("location", location);
            if (StringUtils.isNotBlank(recordType)) {
                params.put("recordType", recordType);
            }

            String recordResp = requester.get(path, params);
            JsonNode recordRespJson = JacksonUtils.parse(recordResp);
            JsonNode recordsJsonArr = recordRespJson.get("records");

            Map<String, Object> queryRecordMap = new HashMap<>();
            queryRecordMap.put("channelCode", code);
            queryRecordMap.put("location", location);


            List<VideoPlaybackResp> result = new ArrayList<>();
            for (JsonNode jsonNode : recordsJsonArr) {
                String beginTimeStr = jsonNode.get("beginTime").asText();
                String endTimeStr = jsonNode.get("endTime").asText();
                queryRecordMap.put("resource", jsonNode.get("file").asText()
                        .replace("[", "%5B")
                        .replace("]", "%5D"));
                queryRecordMap.put("beginTime", beginTimeStr);
                queryRecordMap.put("endTime", endTimeStr);

                String resp = requester.get(playbackPath, queryRecordMap);
                JsonNode respJson = JacksonUtils.parse(resp);
                String uri = respJson.get("uri").asText();
                if (StringUtils.isNotBlank(uri)) {
                    VideoPlaybackResp videoPlaybackResp = new VideoPlaybackResp();
                    videoPlaybackResp.setStartTime(DateUtils.parse(beginTimeStr, DateUtils.FormatType.TZ));
                    videoPlaybackResp.setEndTime(DateUtils.parse(endTimeStr, DateUtils.FormatType.TZ));
                    videoPlaybackResp.setUrl(uri);
                    result.add(videoPlaybackResp);
                }
            }
            return result;
        } catch (Exception e) {
            LOGGER.error("大华9100 获取回放异常", e);
        }
        return Lists.newArrayList();
    }

    /**
     * 以图搜图
     *
     * @param faceImgUrl 图片url
     * @param similarity 相似度 0-100
     * @param codes      查找的设备列表 非必填
     * @param startTime  搜索的时间段 非必填
     * @param endTime    搜索的时间段 非必填
     * @param pageNo     分页参数 非必填
     * @param pageSize   分页参数 非必填
     * @return
     */
    public List<SnapFaceRecordResp.ResultsCls> searchMap(String faceImgUrl, BigDecimal similarity
            , List<String> codes, Date startTime, Date endTime, Integer pageNo, Integer pageSize) {
        String path = "/faceService/query/capture";
        Map<String, Object> conditionMap = new HashMap<>();
        if (startTime != null) {
            conditionMap.put("startCapTime", DateUtils.format(startTime, DateUtils.FormatType.TZ));
        }
        if (endTime != null) {
            conditionMap.put("endCapTime", DateUtils.format(endTime, DateUtils.FormatType.TZ));
        }
        if (CollectionUtils.isNotEmpty(codes)) {
            conditionMap.put("channelCodes", codes);
        }

        try {
            Map<String, Object> params = new HashMap<>();
            if (pageNo != null && pageSize != null) {
                path = path + ("?start=" + (pageNo - 1) * pageSize + 1 + "&limit=" + pageSize);
            }
            params.put("condition", conditionMap);

            String base64Img = ImageUtils.urlToBase64Img(faceImgUrl);
            Map<String, Object> retrievalMap = new HashMap<>();
            retrievalMap.put("faceImage", base64Img);
            retrievalMap.put("threshold", similarity.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP).doubleValue());
            params.put("retrieval", retrievalMap);

            String resp = requester.post(path, params);
            SnapFaceRecordResp parse = JacksonUtils.parse(resp, SnapFaceRecordResp.class);
            return parse.getResults();
        } catch (Exception e) {
            LOGGER.error("大华9100 以图搜图异常", e);
        }
        return Lists.newArrayList();
    }


}
